package com.ruoyi.aitcommon.api;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.aitcommon.anotation.ApiLog;
import com.ruoyi.aitcommon.config.ConfigManager;
import com.ruoyi.aitcommon.utils.ExceptionUtils;
import com.ruoyi.aitcommon.utils.JSONResult;
import com.ruoyi.aitcommon.utils.ObjUtils;
import com.ruoyi.aitcommon.utils.RestServiceUtils;
import com.ruoyi.aitcommon.vo.AIChatVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/ait/common/chat")
public class AIChatOperation {
    @Autowired
    ConfigManager configManager;

    /**
     * AI聊天API接入
     *
     * @param jsonstr 聊天参数
     *
     */
    @ApiLog("AI聊天")
    @PostMapping("/AIChat")
    public JSONObject AIChat(@RequestBody String jsonstr) {
        List<String> retMsg=new ArrayList<>();
        try{
//			参数校验
            ExceptionUtils.checkBlankOrUndefined(jsonstr, "传入参数为空");
            JSONObject json = JSONObject.parseObject(jsonstr);
            String msg=json.getString("msg");
//            获取配置参数url,apikey,model
            final JSONObject parm = (JSONObject) configManager.getContextByParm("appconfig.chat");
            ExceptionUtils.checkBlankOrUndefined(parm, "appconfig.chat 配置为空");
            final String url = parm.getString("url");
            final String apiKey = parm.getString("apiKey");
            final String model = parm.getString("model");
//            构造header
            JSONObject header=new JSONObject();
            header.put("Content-Type","application/json");
            header.put("Authorization","Bear "+apiKey);
//            构造body
            AIChatVO body=new AIChatVO();
            body.setModel(model);
            body.addMessage("system","You are a helpful assistant.");
            body.addMessage("user",msg);
//            调用接口
            final JSONObject ret = RestServiceUtils.post(url, header, (JSONObject) JSONObject.toJSON(body));
//            处理返回
            final JSONArray choices = ret.getJSONArray("choices");
            if(ObjUtils.isNotBlank(choices)){
                for (Object chobj:choices) {
                    JSONObject chjson=(JSONObject) chobj;
                    final JSONObject message = chjson.getJSONObject("message");
                    retMsg.add(message.getString("content"));
                }
            }
            return JSONResult.success(retMsg);
        }catch (Exception ex){
            return JSONResult.error(ex.getMessage());
        }
    }
}
